<script setup lang="ts">
import { type BusData, type FlightData, type HotelData, QueryType, type CustomerData } from "../../../types/DataTypes.ts"
import { type DataKeyType, DataKey } from "../../../types/KeyTypes.ts";
import { inject, reactive, ref, watch } from "vue";
import { api } from "../../../api/Api.ts"
import type { FormInstance} from "element-plus";
import { ElMessage } from "element-plus";
// 导入外部验证规则
import {
  busRules,
  flightRules,
  hotelRules,
  customerRules
} from "../../../rules/DataInsertRules.ts";

const props = defineProps<{
  queryType: QueryType,
  showInsert: boolean,
}>()

const emit = defineEmits<{
  'cancel': [boolean]
}>()

const loading = ref(false);
// 表单引用
const busFormRef = ref<FormInstance>();
const flightFormRef = ref<FormInstance>();
const hotelFormRef = ref<FormInstance>();
const customerFormRef = ref<FormInstance>(); // 添加客户表单引用

// 巴士表单数据
const busData = reactive<BusData>({
  location: '',
  price: 0.00,
  availBus: 0,
  totalBus: 10
})

// 航班表单数据
const flightData = reactive<FlightData>({
  flightNum: '',
  fromCity: '',
  arivCity: '',
  price: 0.00,
  availSeat: 0,
  totalSeat: 100
})

// 酒店表单数据
const hotelData = reactive<HotelData>({
  location: '',
  price: 0.00,
  availRoom: 0,
  totalRoom: 50
})

// 客户表单数据
const customerData = reactive<CustomerData>({
  customerId: '',
  customerName: '',
  // 根据CustomerApi.ts中的API，可能需要其他字段
})

const { isNeedUpdate } = inject<DataKeyType>(DataKey) as DataKeyType;

const handleCancel = () => {
  emit('cancel', false)
}

// 重置巴士表单数据
const resetBusFormData = (formRef: FormInstance | undefined) => {
  busData.location = '';
  busData.price = 0.00;
  busData.availBus = 0;
  busData.totalBus = 10;

  // 清除验证状态
  if (formRef) {
    formRef.resetFields();
  }
}

// 重置航班表单数据
const resetFlightFormData = (formRef: FormInstance | undefined) => {
  flightData.flightNum = '';
  flightData.fromCity = '';
  flightData.arivCity = '';
  flightData.price = 0.00;
  flightData.availSeat = 0;
  flightData.totalSeat = 100;

  // 清除验证状态
  if (formRef) {
    formRef.resetFields();
  }
}

// 重置酒店表单数据
const resetHotelFormData = (formRef: FormInstance | undefined) => {
  hotelData.location = '';
  hotelData.price = 0.00;
  hotelData.availRoom = 0;
  hotelData.totalRoom = 50;

  // 清除验证状态
  if (formRef) {
    formRef.resetFields();
  }
}

// 重置客户表单数据
const resetCustomerFormData = (formRef: FormInstance | undefined) => {
  customerData.customerId = '';
  customerData.customerName = '';

  // 清除验证状态
  if (formRef) {
    formRef.resetFields();
  }
}

// 根据查询类型重置表单
const resetFormData = () => {
  switch (props.queryType) {
    case QueryType.BusQuery:
      resetBusFormData(busFormRef.value);
      break;
    case QueryType.FlightQuery:
      resetFlightFormData(flightFormRef.value);
      break;
    case QueryType.HotelQuery:
      resetHotelFormData(hotelFormRef.value);
      break;
    case QueryType.CustomersQuery:
      resetCustomerFormData(customerFormRef.value);
      break;
    case QueryType.ReservationQuery:
      // 其他类型的重置逻辑
      break;
  }
}

const handleInsert = () => {
  switch (props.queryType) {
    case QueryType.BusQuery:
      handleBusInsert();
      break;
    case QueryType.FlightQuery:
      handleFlightInsert();
      break;
    case QueryType.HotelQuery:
      handleHotelInsert();
      break;
    case QueryType.CustomersQuery:
      handleCustomerInsert();
      break;
    case QueryType.ReservationQuery:
      break;
    default:
      break;
  }
}

// 提交巴士表单数据
const handleBusInsert = async () => {
  if (!busFormRef.value) return;
  const valid = await busFormRef.value.validate().catch(() => false);

  if (!valid) {
    ElMessage.error('请填写正确的巴士数据');
    return;
  }
  loading.value = true;
  try {
    const response = await api.bus.addBus(busData);

    if (response.success) {
      ElMessage.success('巴士数据添加成功');
      resetBusFormData(busFormRef.value);
      emit('cancel', false);
      isNeedUpdate.value = true;
    } else {
      ElMessage.error(response.message || '添加巴士数据失败');
    }
  } catch (error) {
    console.error('添加巴士数据出错:', error);
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    loading.value = false;
  }
}

// 提交航班表单数据
const handleFlightInsert = async () => {
  if (!flightFormRef.value) return;
  const valid = await flightFormRef.value.validate().catch(() => false);

  if (!valid) {
    ElMessage.error('请填写正确的航班数据');
    return;
  }
  loading.value = true;
  try {
    const response = await api.flight.addFlight(flightData);

    if (response.success) {
      ElMessage.success('航班数据添加成功');
      resetFlightFormData(flightFormRef.value);
      emit('cancel', false);
      isNeedUpdate.value = true;
    } else {
      ElMessage.error(response.message || '添加航班数据失败');
    }
  } catch (error) {
    console.error('添加航班数据出错:', error);
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    loading.value = false;
  }
}

// 提交酒店表单数据
const handleHotelInsert = async () => {
  if (!hotelFormRef.value) return;
  const valid = await hotelFormRef.value.validate().catch(() => false);

  if (!valid) {
    ElMessage.error('请填写正确的酒店数据');
    return;
  }
  loading.value = true;
  try {
    const response = await api.hotel.addHotel(hotelData);

    if (response.success) {
      ElMessage.success('酒店数据添加成功');
      resetHotelFormData(hotelFormRef.value);
      emit('cancel', false);
      isNeedUpdate.value = true;
    } else {
      ElMessage.error(response.message || '添加酒店数据失败');
    }
  } catch (error) {
    console.error('添加酒店数据出错:', error);
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    loading.value = false;
  }
}

// 提交客户表单数据
const handleCustomerInsert = async () => {
  if (!customerFormRef.value) return;
  const valid = await customerFormRef.value.validate().catch(() => false);

  if (!valid) {
    ElMessage.error('请填写正确的客户数据');
    return;
  }
  loading.value = true;
  try {
    const response = await api.customer.addCustomer(customerData);

    if (response.success) {
      ElMessage.success('客户数据添加成功');
      resetCustomerFormData(customerFormRef.value);
      emit('cancel', false);
      isNeedUpdate.value = true;
    } else {
      ElMessage.error(response.message || '添加客户数据失败');
    }
  } catch (error) {
    console.error('添加客户数据出错:', error);
    ElMessage.error('网络错误，请稍后重试');
  } finally {
    loading.value = false;
  }
}

// 监听对话框关闭，重置表单
watch(() => props.showInsert, (newVal) => {
  if (!newVal) {
    resetFormData();
  }
});
</script>

<template>
  <el-dialog
      :model-value="showInsert"
      :title="`插入新数据`"
      width="300"
      :before-close="handleCancel"
      @keyup.enter="handleInsert"
  >
    <!-- 巴士表单 -->
    <el-form
        ref="busFormRef"
        :model="busData"
        :rules="busRules"
        v-if="queryType === QueryType.BusQuery"
        label-width="100px"
    >
      <el-form-item label="地点" prop="location">
        <el-input
            v-model="busData.location"
            placeholder="请输入巴士运行地点"
            clearable
        />
      </el-form-item>
      <el-form-item label="价格" >
        <el-input-number v-model="busData.price" :step="5" :min="0" :precision="2">
          <template #suffix>
            <span>元</span>
          </template>
        </el-input-number>
      </el-form-item>
      <el-form-item label="可用巴士">
        <el-input-number v-model="busData.availBus" :step="1" :max="busData.totalBus" :min="0"/>
      </el-form-item>
      <el-form-item label="巴士总数">
        <el-input-number v-model="busData.totalBus" :step="1" :min="busData.availBus" />
      </el-form-item>
    </el-form>

    <!-- 航班表单 -->
    <el-form
        ref="flightFormRef"
        :model="flightData"
        :rules="flightRules"
        v-else-if="queryType === QueryType.FlightQuery"
        label-width="100px"
    >
      <el-form-item label="航班号" prop="flightNum">
        <el-input
            v-model="flightData.flightNum"
            placeholder="请输入航班号"
            clearable
        />
      </el-form-item>
      <el-form-item label="出发城市" prop="fromCity">
        <el-input
            v-model="flightData.fromCity"
            placeholder="请输入出发城市"
            clearable
        />
      </el-form-item>
      <el-form-item label="到达城市" prop="arivCity">
        <el-input
            v-model="flightData.arivCity"
            placeholder="请输入到达城市"
            clearable
        />
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input-number
            v-model="flightData.price"
            :step="100"
            :min="0"
            :precision="2"
            controls-position="right"
        >
          <template #suffix>
            <span>元</span>
          </template>
        </el-input-number>
      </el-form-item>
      <el-form-item label="可用座位" prop="availSeat">
        <el-input-number
            v-model="flightData.availSeat"
            :step="1"
            :min="0"
            :max="flightData.totalSeat"
            controls-position="right"
        />
      </el-form-item>
      <el-form-item label="座位总数" prop="totalSeat">
        <el-input-number
            v-model="flightData.totalSeat"
            :step="10"
            :min="flightData.availSeat"
            controls-position="right"
        />
      </el-form-item>
    </el-form>

    <!-- 酒店表单 -->
    <el-form
        ref="hotelFormRef"
        :model="hotelData"
        :rules="hotelRules"
        v-else-if="queryType === QueryType.HotelQuery"
        label-width="100px"
    >
      <el-form-item label="位置" prop="location">
        <el-input
            v-model="hotelData.location"
            placeholder="请输入酒店位置"
            clearable
        />
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input-number
            v-model="hotelData.price"
            :step="50"
            :min="0"
            :precision="2"
            controls-position="right"
        >
          <template #suffix>
            <span>元</span>
          </template>
        </el-input-number>
      </el-form-item>
      <el-form-item label="可用房间" prop="availRoom">
        <el-input-number
            v-model="hotelData.availRoom"
            :step="1"
            :min="0"
            :max="hotelData.totalRoom"
            controls-position="right"
        />
      </el-form-item>
      <el-form-item label="房间总数" prop="totalRoom">
        <el-input-number
            v-model="hotelData.totalRoom"
            :step="50"
            :min="hotelData.availRoom"
            controls-position="right"
        />
      </el-form-item>
    </el-form>

    <!-- 客户表单 -->
    <el-form
        ref="customerFormRef"
        :model="customerData"
        :rules="customerRules"
        v-else-if="queryType === QueryType.CustomersQuery"
        label-width="100px"
    >
      <el-form-item label="客户姓名" prop="customerName">
        <el-input
            v-model="customerData.customerName"
            placeholder="请输入客户姓名"
            clearable
        />
      </el-form-item>
      <el-form-item label="客户ID" prop="customerId">
        <el-input
            v-model="customerData.customerId"
            placeholder="请输入客户ID"
            clearable
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel" :disabled="loading">取消</el-button>
        <el-button type="primary" @click="handleInsert" :loading="loading">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
:deep(.el-form-item__label) {
  font-weight: 500;
}
</style>